import { useEffect, useRef } from 'react';
import { Button, Select, Input, message, Collapse, Radio, Spin, Result, Image } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { Popup } from 'antd-mobile';

import InputItem from './InputItemWrap';

import icon_7 from '@/assets/images/icons/7.png';
import icon_cat from '@/assets/images/icons/cat.png';
import icon_family from '@/assets/images/icons/family.png';
import { Link } from 'react-router-dom';
import { compose } from 'redux';
import Cookies from 'js-cookie';

const icons = {
  '711-shop': icon_7,
  'family-mart': icon_family,
  cat: icon_cat,
};

const Wrap = css.div`
  margin: 16px 0;
  .input-item-wrap{
    >.title{
      font-weight: 600;
      font-size: 14px;
      line-height: 20px;
      color: #000;
      margin: 8px 0;
    }
    >.cont{

    }
    & + .input-item-wrap{
      margin-top: 16px;
    }
  }
  .selector-wrap{
    ${_gb.flex()};
    flex-wrap: wrap;
    >a{
      width: 48%;
      display: inline-block;
      font-weight: 400;
      font-size: 14px;
      line-height: 20px;
      padding: 12px;
      border: 1px solid #ddd;
      color: #000;
      text-align: center;
      & + a{
        margin-left: 8px;
      }
      &:nth-child(n + 2){
        margin: 8px 0 0 0;
      }
      &.active{
        border-color: #000;
      }
      &.composes-item{
        width: 100%;
        text-align: left;
        ${_gb.flex()};
        >span:first-child{
          width: 70%;
        }
        >span:last-child{
          color: #CD4D43;
          display: inline-block;
          width: 30%;
        }
      }
    }
    &.pay-selector-wrap{
      flex-wrap: nowrap;
      >a{
       width: 31%;
        & + a{
          margin-left: 0;
        }
        &:nth-child(n + 2){
          margin: 0;
        }
      }
    }
  }
  .btn-wrap{
    margin: 32px 0 8px 0;
  }
  .tips-cat{
    width: 100%;
    height: 34px;
    font-weight: 400;
    font-size: 12px;
    line-height: 34px;
    color: #CD4D43;
    text-align: center;
    margin: 16px 0;
    background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), #CD4D43;
  }
  .attr-group{
    h2{
      font-size: 14px;
      margin: 12px 0 6px;
    }
    .ant-radio-wrapper{
      width: 50%;
    }
    .img-wrap{
      width: 120px;
      height: 120px;
      overflow: hidden;
      .ant-image{
        width: 100%;
        height: 100%;
      }
      img{
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  .ant-radio-group.ant-radio-group-outline{
    ${_gb.flex()};
    flex-wrap: wrap;
    justify-content: flex-start;
  }
`;

const Order = ({ goodsId, sendLog, composes = [] }) => {
  const [loading, setLoading] = useState(false);
  const [popupVisible, setPopupVisible] = useState(false);
  const [shop, setShop] = useState('cat');
  const [curCompose, setCurCompose] = useState(''); // 当前组合id
  const [pickAddress, setPickAddress] = useState([]); // 取货地址
  const [addrCode, setCurAddrCode] = useState(''); // 711 shop code
  const [addressInfo, setAddressInfo] = useState({}); // 用户填写地址
  const [attrs, setAttrs] = useState({}); // 用户选择尺码颜色等
  const [curPrice, setCurPrice] = useState('');
  const isTracked = useRef(false);
  const composesRef = useRef();
  const { data: deliverInfo } = useSwr(_api.info, (url) => _ajax.get(url, { params: { region_code: 'zh_tw' } }));
  const delivers = { cat: [] };
  const setValue = (obj, key) => {
    if (!obj[key]) {
      obj[key] = {};
    }
  };

  /*
   * @Desc: 事件发送
   * @params: {String}
   * @return: {Object}
  */
  const sendEvent = (params = {}) => {
    const pixel = Cookie.get('pixel')
    if(!pixel) return;
    _ajax.post(_api.postEvent, {
      ...params,
      pixel,
      fbc: Cookie.get('_fbc'),
      pbp: Cookie.get('_fbp'),
      src_url: location.href
    })
};

  useEffect(() => {
    composesRef.current && composesRef.current?.click();
  }, [composesRef.current, composes]);

  deliverInfo?.data?.forEach((item) => {
    setValue(delivers, item.esp_name);
    setValue(delivers[item.esp_name], item.city);
    setValue(delivers[item.esp_name][item.city], item.region);
    setValue(delivers[item.esp_name][item.city][item.region], `${item.shop_name}-${item.address}#${item.code}`);
  });
  const handleDeliverSelect = (item) => {
    setShop(item);
    setPickAddress([]);
  };
  const handlePickAddressChange = (key, value) => {
    const addr = [...pickAddress].slice(0, key);
    if (key === 2) {
      const address = value.split('#');
      addr[key] = address[0];
      setCurAddrCode(address[1]);
    } else {
      addr[key] = value;
    }
    setPickAddress(addr);
  };
  const handleInfoChange = (key, e) => {
    const value = e.target.value.trim();
    const info = { ...addressInfo, [key]: value };
    setAddressInfo(info);
  };
  const handleBlur = (key, e) => {
    const value = e.target.value.trim();
    if (!value) return;
    try {
      sendLog({
        op: {
          userInput: {
            type: { user_name: 10, user_mobile: 11, user_address: 12, user_remark: 13 }[key],
            is_paste: e?.nativeEvent?.inputType === 'insertFromPaste' ? true : false,
            value,
          },
        },
      });
    } catch (error) {
      console.log(error);
    }
  };
  const reset = () => {
    setShop('cat');
    setAttrs({});
    setPickAddress([]);
    setAddressInfo({});
  };
  const handleComposeChange = (value) => {
    setCurCompose(value?.sn);
    setCurPrice(value?.price);
    setAttrs({});
  };
  const handleAttrChange = (key, e) => {
    const value = e.target.value;
    const attr = { ...attrs, [key]: value };
    setAttrs(attr);
  };
  // 购买
  const handleBuy = async () => {
    const { user_name, user_mobile, user_address, remarks } = addressInfo;
    const [order_city, order_region, address] = pickAddress;
    const compose_skus = Object.values(attrs).join('#');
    const selectComposes = composes?.find((item) => item.sn === curCompose)?.products;
    const composesLength = selectComposes?.reduce((sum, item) => {
      if (item?.attris?.length) {
        sum += item?.attris?.length * (item?.num ?? 1);
      }
      if (item?.displays) {
        sum += 1 * (item?.num ?? 1);
      }
      return sum;
    }, 0);
    if (!curCompose) {
      message.info('請選擇購買方式');
      return;
    }
    if (composesLength !== Object.values(attrs)?.length) {
      message.info('請選擇尺碼顏色');
      return;
    }
    if (!user_name) {
      message.info('請填寫您的姓名');
      return;
    }
    if (!user_mobile) {
      message.info('填寫您的手機號碼');
      return;
    }
    if (shop === 'cat' && !user_address) {
      message.info('填寫您的地址');
      return;
    }
    if (shop !== 'cat' && (!order_city || !order_region || !address)) {
      message.info('選擇您的取貨地址');
      return;
    }
    const data = {
      compose_sn: curCompose,
      user_name,
      user_mobile,
      address: shop === 'cat' ? user_address : address,
      compose_skus,
      remarks,
      order_country: '中国',
      order_city,
      order_region,
      order_area: '集美',
      esp_id: { '711-shop': 1, 'family-mart': 2, cat: 3 }[shop],
    };
    shop !== 'cat' && (data['store_code'] = addrCode);
    setLoading(true);
    setPopupVisible(true);
    try {
      const res = await _ajax.post(_api.order, data);
      if (res.code === 200) {
        message.success('訂單提交成功');
        window.fbq('track', 'PageView');
        sendEvent({
          event: 'page_view',
        })
        window.fbq('track', 'Purchase', {
          currency: 'NTD',
          contents: [{ id: curCompose, quantity: 1 }],
          value: curPrice,
        });
        sendEvent({
          event: 'purchase',
          compose_sn: curCompose
        })
      }
      setLoading(false);
    } catch (error) {
      console.log(error);
      setLoading(false);
      message.error(`未知異常，請稍後再試 ${error?.message || error}`);
    }
  };
  const handleModalClose = () => {
    setPopupVisible(false);
    reset();
  };
  return (
    <Wrap>
      <div className="deliver">
        <a style={{ fontSize: 0 }} name="buy">
          buy
        </a>
        <InputItem title="購買方式：">
          <div id="sku" className="selector-wrap">
            {composes?.map((item, index) => (
              <a
                className={classnames('selector', 'composes-item', { active: curCompose === item?.sn })}
                onClick={() => handleComposeChange(item)}
                key={index}
                ref={index === 0 ? composesRef : null}
              >
                <span>{item.name}</span>
                <span>NT$ {item.price}</span>
              </a>
            ))}
          </div>
        </InputItem>
        <InputItem title="顏色尺碼">
          <Collapse style={{ marginTop: 12 }} defaultActiveKey={[0, 1, 2, 3, 4, 5]} expandIconPosition="end">
            {composes
              ?.find((item) => item.sn === curCompose)
              ?.products?.map((item, index) => (
                <Collapse.Panel key={index} header={`${item.name}`}>
                  {/* <Collapse.Panel key={index} header={`#${index + 1} ${item.name}`}> */}
                  {new Array(item?.num || 0).fill(1).map((prod, prodIndex) => (
                    <div key={prodIndex}>
                      {item?.attris?.map((attr, attrIndex) => (
                        <div className="attr-group" key={attrIndex}>
                          <h2>
                            {attr?.key}
                            {/* #{index + 1}-{prodIndex + 1} {attr?.key} */}
                          </h2>
                          <Radio.Group
                            value={attrs?.[`${index + 1}_${prodIndex + 1}_${attr?.key}`]}
                            onChange={(e) => handleAttrChange(`${index + 1}_${prodIndex + 1}_${attr?.key}`, e)}
                          >
                            {attr?.value?.split('#')?.map((attrItem) => (
                              <Radio key={attrItem} value={attrItem}>
                                {attrItem}
                              </Radio>
                            ))}
                          </Radio.Group>
                        </div>
                      ))}
                      <h2 style={{ fontSize: '14px' }}>
                        顏色
                        {/* #{index + 1}-{prodIndex + 1} 顏色 */}
                      </h2>
                      <Radio.Group
                        value={attrs?.[`${index + 1}_${prodIndex + 1}_color`]}
                        onChange={(e) => handleAttrChange(`${index + 1}_${prodIndex + 1}_color`, e)}
                      >
                        {item?.displays?.map((attr, attrIndex) => (
                          <div className="attr-group" key={attrIndex}>
                            <Radio key={attr?.key} value={attr?.key}>
                              <div className="img-wrap">
                                {/* <img src={attr?.value} alt="" /> */}
                                <Image src={attr?.value} />
                              </div>
                              {attr?.key}
                            </Radio>
                          </div>
                        ))}
                      </Radio.Group>
                    </div>
                  ))}
                </Collapse.Panel>
              ))}
          </Collapse>
        </InputItem>
        <InputItem title="取貨付款方式：">
          <div className="selector-wrap pay-selector-wrap">
            {Object.keys(delivers)?.map((item, index) => (
              <a
                className={classnames('selector', { active: shop === item })}
                onClick={() => handleDeliverSelect(item)}
                key={index}
                style={{ background: `url(${icons[item]}) 12px center / 20px no-repeat` }}
              >
                {{ cat: '黑貓/新竹', '711-shop': '7-11取貨', 'family-mart': '全家取貨' }[item]}
              </a>
            ))}
          </div>
        </InputItem>
        {shop === 'cat' && <div className="tips-cat">我們會宅配送貨到您府上，請您注意查收</div>}
        <InputItem title="姓名：">
          <Input
            value={addressInfo?.user_name}
            onChange={(value) => handleInfoChange('user_name', value)}
            onBlur={(value) => handleBlur('user_name', value)}
            placeholder="請填寫您的姓名"
          />
        </InputItem>
        <InputItem title="手機號碼：">
          <Input
            value={addressInfo?.user_mobile}
            type="number"
            onChange={(value) => handleInfoChange('user_mobile', value)}
            onBlur={(value) => handleBlur('user_name', value)}
            placeholder="填寫您常用的手機號碼"
          />
        </InputItem>
        {shop !== 'cat' && (
          <InputItem title="選擇地區">
            <Select
              value={pickAddress[0]}
              onChange={(value) => handlePickAddressChange(0, value)}
              size="large"
              style={{ width: '49%' }}
              placeholder="---請選取市、縣---"
            >
              {Object.keys(delivers[shop] || {})?.map((item) => (
                <Select.Option key={item} value={item}>
                  {item}
                </Select.Option>
              ))}
            </Select>
            <Select
              value={pickAddress[1]}
              onChange={(value) => handlePickAddressChange(1, value)}
              size="large"
              style={{ width: '49%', marginLeft: '2%' }}
              placeholder="---請選取區、縣、鄉---"
            >
              {Object.keys(delivers?.[shop]?.[pickAddress[0]] || {})?.map((item) => (
                <Select.Option key={item} value={item}>
                  {item}
                </Select.Option>
              ))}
            </Select>
            <Select
              value={pickAddress[2]}
              onChange={(value) => handlePickAddressChange(2, value)}
              size="large"
              style={{ width: '100%', marginTop: '8px' }}
              placeholder="---請選取門市名稱和地址---"
            >
              {Object.keys(delivers?.[shop]?.[pickAddress[0]]?.[pickAddress?.[1]] || {})?.map((item) => (
                <Select.Option key={item} value={item}>
                  {item?.split('#')?.[0]}
                </Select.Option>
              ))}
            </Select>
          </InputItem>
        )}
        <InputItem title="詳細地址：">
          <Input
            value={shop === 'cat' ? addressInfo?.user_address : pickAddress.join()}
            onChange={(value) => handleInfoChange('user_address', value)}
            onBlur={(value) => handleBlur('user_name', value)}
            disabled={shop !== 'cat'}
            placeholder="請填寫您的詳細地址"
          />
        </InputItem>
        <InputItem title="留言備註：">
          <Input
            value={addressInfo?.remarks}
            onChange={(value) => handleInfoChange('remarks', value)}
            onBlur={(value) => handleBlur('user_name', value)}
            placeholder="如備用電話、商品數量、收貨時間等需求請留言"
          />
        </InputItem>
        <div className="btn-wrap">
          <Button onClick={handleBuy} type="primary" block>
            立即下單
          </Button>
        </div>
      </div>
      <Popup
        visible={popupVisible}
        onMaskClick={handleModalClose}
        bodyStyle={{ height: '85vh', background: '#fff', overflowY: 'auto' }}
      >
        <div className="popup-wrap">
          <div style={{ padding: '16px' }} header="訂單詳情">
            <h2>訂單詳情</h2>
            <div
              key="name"
              title="姓名"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                姓名
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {' '}
                {addressInfo?.user_name}
              </div>
            </div>
            <div
              key="phone"
              title="手機號碼"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                手機號碼
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {' '}
                {addressInfo?.user_mobile}
              </div>
            </div>
            <div
              key="sku"
              title="購買方式"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                購買方式
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {' '}
                {Object.values(attrs).join('#')}
              </div>
            </div>
            <div
              key="deliver"
              title="取貨方式"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                取貨方式
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {' '}
                {{ cat: '黑貓/新竹', '711-shop': '7-11取貨', 'family-mart': '全家取貨' }[shop]}
              </div>
            </div>
            <div
              key="address"
              title="詳細地址"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                詳細地址
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {shop === 'cat' ? addressInfo?.user_address : `${pickAddress?.join()}`}
              </div>
            </div>
            <div
              key="remark"
              title="留言備註"
              style={{ margin: '0', padding: '8px 0', borderTop: '1px solid rgba(0, 0, 0, .06)' }}
            >
              <div className="title" style={{ color: '#999' }}>
                留言備註
              </div>
              <div className="cont" style={{ fontSize: '16px', marginTop: '2px' }}>
                {' '}
                {addressInfo?.remarks}
              </div>
            </div>
          </div>
          <div style={{ textAlign: 'center' }} className="btn-wrap">
            {loading ? (
              <>
                <Spin indicator={<LoadingOutlined style={{ fontSize: 24 }} spin delay={3000} />} />
                <p style={{ paddingTop: '16px' }}>訂單提交中...</p>
              </>
            ) : (
              <Result style={{ padding: '0px 0 28px' }} status="success" title="訂單提交成功" />
            )}
          </div>
        </div>
      </Popup>
    </Wrap>
  );
};

export default Order;
